
target_phase = rand * 2 * pi - pi; % 生成一个 -pi 到 pi 之间的随机相位  
max_iterations = 10; % 设置最大迭代次数  
% closest_phase_found = binary_search_closest_phase(target_phase, max_iterations);  
% fprintf('Target Phase: %.6f, Closest Phase Found: %.6f\n', target_phase, closest_phase_found);

% scatterplot(Fre_out);
load("fre_out.mat")
Constell = 2;
max_iterations = 20;

closest_phase = binary_search_closest_phase(max_iterations,Fre_out,Constell);
closest_phase
scatterplot(Fre_out.*exp(1i*closest_phase));
function closest_phase = binary_search_closest_phase(max_iterations,fre_out,Constell)  
    % target_phase: 目标相位，需要在 -pi 到 pi 之间找到最接近的值  
    % max_iterations: 最大迭代次数  

    % 定义搜索区间  
    lower_bound = -pi/4;  
    upper_bound = pi/4;  

    % 初始化最接近的相位为区间的中点  
    closest_phase = (lower_bound + upper_bound) / 2;  

    % 进行二分查找的迭代  
    for iter = 1:max_iterations  
        % 计算当前区间的中点  
        mid_phase = (lower_bound + upper_bound) / 2;  
        
        %二分查找
        error = cal_calculate(fre_out,mid_phase,Constell);
        if error>=cal_calculate(fre_out,upper_bound,Constell)
            lower_bound = mid_phase;
        else
            upper_bound = mid_phase;
        end

        closest_phase = mid_phase;
    end  
end  

% function error = cal_error(Fre_out,target_phase,Constell)\

function error = cal_calculate(Fre_out,fre_offset,Constell)
    Fre_out_offset = Fre_out*exp(1i*fre_offset);
    QAM_symbol=qammod(0:2^Constell-1,2^Constell)';
    cal_mat = repmat(QAM_symbol,1,length(Fre_out));
    % error_mat = mod(angle(Fre_out_offset)-angle(cal_mat),2*pi)-pi;
    error_mat = Fre_out_offset-cal_mat;
    [~,flag] = min(abs(error_mat).^2);
    %获得理想相位
    ideal_qam = QAM_symbol(flag).';
    % scatterplot(ideal_qam);
    %计算误差
    error = sum(abs((ideal_qam-Fre_out_offset)).^2);
end


%%
% close all;
% clear;
% load("fre_out.mat")
%归一化Fre_out
% Constell = 2;
% Fre_out = Fre_out/max(abs(Fre_out));
% scatterplot(Fre_out);
% % Fre_out = Fre_out*exp(1i*2);
% 
% phase_list = 0:2*pi/200:2*pi;
% error_total = zeros(1,length(0:2*pi/200:2*pi));
% i = 0;
% for fre_offset = phase_list
%     % fre_offset = 1;
%     Fre_out_offset = Fre_out*exp(1i*fre_offset);
%     QAM_symbol=qammod(0:2^Constell-1,2^Constell)';
%     cal_mat = repmat(QAM_symbol,1,length(Fre_out));
%     % error_mat = mod(angle(Fre_out_offset)-angle(cal_mat),2*pi)-pi;
%     error_mat = Fre_out_offset-cal_mat;
%     [min_phase_mat,flag] = min(abs(error_mat).^2);
%     %获得理想相位
%     ideal_qam = QAM_symbol(flag).';
%     % scatterplot(ideal_qam);
%     %计算误差
%     error = sum(abs((ideal_qam-Fre_out_offset)).^2);
%     error_total(i+1) = error;
%     i = i+1;
% end
% figure;
% plot(phase_list,error_total);
% [~,min_phase] = min(error_total);
% 
% scatterplot(Fre_out*exp(1i*phase_list(min_phase)));
% disp(phase_list(min_phase));

















